package com.cn.jinl.service;

import com.cn.jinl.api.IHealthCheckService;
import com.cn.jinl.conf.Config;
import com.cn.jinl.dao.HealthCheckMapper;
import com.cn.jinl.domain.HealthCheck;
import com.cn.jinl.domain.HealthCheckExample;
import com.cn.jinl.utils.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created On : 2024/1/4.
 * <p>
 * Author : Huiyan
 * <p>
 * Description: HealthCheckServiceImpl
 */
@EnableScheduling
@Service
public class HealthCheckServiceImpl implements IHealthCheckService {

    @Autowired
    private HealthCheckMapper healthCheckMapper;

    @Autowired
    private Config config;


    @Override
    public List<HealthCheck> getHealthCheckList(QueryForm queryForm) throws Exception {
        List<HealthCheck> list = healthCheckMapper.getLastestData(queryForm);
        return list;
    }

    @Override
    public String uploadNewHealthCheck(HealthCheck healthCheck) throws Exception {

        if (StringUtils.isEmpty(healthCheck.getPersonnelId())){
            return "";
        }

        int mothCount = healthCheck.getMothCount();
        if (mothCount <= 0){
            return "有效期格式异常！";
        }


        if ("1".equals(healthCheck.getFirstCheck())){
            String id = healthCheck.getId();
            if (StringUtils.isEmpty(id)){
                return "id is null";
            }
            HealthCheck check = new HealthCheck();
            check.setStatus(Constants.DEL_STATUS);
            HealthCheckExample example = new HealthCheckExample();
            example.createCriteria().andIdEqualTo(id);
            int count = healthCheckMapper.updateByExampleSelective(check,example);
            if (count<=0){
                return "更新异常！！！";
            }
        }

        healthCheck.setFirstCheck("2");

        //generate end_check_time
        String checkTime = healthCheck.getCheckTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date checkDate = simpleDateFormat.parse(checkTime);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(checkDate);
        calendar.add(Calendar.MONTH,mothCount);
        String endCheckTime = simpleDateFormat.format(calendar.getTime());
        healthCheck.setEndCheckTime(endCheckTime);

        //generate task_status
        String taskStatus = "";
        Date now = new Date();
        Date endTime = simpleDateFormat.parse(endCheckTime);
        long day = (endTime.getTime() - now.getTime())/(1000L*24L*3600L);
        if (day <= 30 && day > 0){
            taskStatus = "2";
        }else if (day < 0){
            taskStatus = "3";
        }else {
            taskStatus = "1";
        }
        healthCheck.setTaskStatus(taskStatus);

        //generate id
        healthCheck.setId(CommonUtil.generateRandomNum("health_check-"));

        int count = healthCheckMapper.insertSelective(healthCheck);

        return CommonUtil.outStr(count);
    }

    @Override
    public String addHealthCheck(String personnelId) throws Exception {
        if (StringUtils.isEmpty(personnelId)){
            return "";
        }

        HealthCheck healthCheck = new HealthCheck();
        healthCheck.setId(CommonUtil.generateRandomNum("health_check-"));
        healthCheck.setPersonnelId(personnelId);
        healthCheck.setFirstCheck("1");
        int count = healthCheckMapper.insertSelective(healthCheck);
        return CommonUtil.outStr(count);
    }

    @Override
    public List<HealthCheck> getHealthCheckLogList(QueryForm queryForm) throws Exception {


        return healthCheckMapper.selectLogs(queryForm);
    }

    @Override
    public void exportHealthCheckExcel(QueryForm queryForm, HttpServletResponse response) throws Exception {
        List<HealthCheck> list =this.getHealthCheckList(queryForm);
        if (CollectionsUtil.isEmpty(list)){
            return;
        }
        Map<String,Object> result = Maps.newHashMap();
        result.put("check", list);
        String fileName = CommonUtil.generateRandomNum("health-")+".xlsx";
        String filePath = config.filePath+fileName;
        TemplateExcelUtils.downLoadExcel(filePath,"健康检疫.xlsx",result,"health_check.xlsx", response);

    }

    @Override
    public Integer countHealthCheckNear() throws Exception {
        int count = healthCheckMapper.countHealthCheckNear();
        return count;
    }

    // 1h interval
    @Scheduled(cron = "0 0 */1 * * ?")
    public void updateHealthCheckStatus() throws Exception{
        HealthCheckExample example = new HealthCheckExample();
        //not first inspection & latest data in table
        List<HealthCheck> healthChecks = healthCheckMapper.selectLatestCheckedList();

        if (CollectionsUtil.isEmpty(healthChecks)){
            return;
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        List<HealthCheck> updates = Lists.newArrayList();
        for (HealthCheck healthCheck : healthChecks){
            String taskStatus = "";
            String endCheckTime = healthCheck.getEndCheckTime()+" 23:59:59";
            if (StringUtils.isEmpty(endCheckTime)){
                continue;
            }
            Date endTime = simpleDateFormat.parse(endCheckTime);
            long day = (endTime.getTime()-now.getTime())/(1000L*24L*3600L);
            if (day <= 30 && day > 0){
                taskStatus = "2";
            }else if (day < 0){
                taskStatus = "3";
            }

            if (StringUtils.isNotEmpty(taskStatus)){
                HealthCheck update = new HealthCheck();
                update.setId(healthCheck.getId());
                update.setTaskStatus(taskStatus);
                updates.add(update);
            }
        }

        if (!CollectionsUtil.isEmpty(updates)){
            healthCheckMapper.batchUpdateCheckHealthStatus(updates);
        }

    }





}
